#include "TCP.h"

void *pthread_serve_read(void * soc);
void *pthread_serve_write(void * soc);

int main(int argc, char const *argv[])
{   
    if (argc != 3)
    {
       printf("格式错误：【%s】 端口 ip地址",argv[0]);
       return -1;
    }
    TCP_soc soc;
    soc = serve_init(atoi(argv[1]) ,argv[2] );
    // 数据收发
    printf("开启聊天\n");
    pthread_t Tid[2];
    pthread_create(&Tid[0] , NULL , pthread_serve_read , (void *)&soc );
    pthread_create(&Tid[1] , NULL , pthread_serve_write , (void *)&soc );

    pthread_join(Tid[0],NULL);
    pthread_join(Tid[1],NULL);


    // 关闭套接字
    close_se_cl(&soc , NULL);
    return 0;
}

void* pthread_serve_read(void * soc)
{   
    TCP_soc soc_1 = *(TCP_soc*)soc;
    char buf[128]; 

    while (1)
    {
              
        memset(buf, 0, sizeof(buf));
        read(soc_1.acc_fd, buf, sizeof(buf));
        if (strlen(buf)==0)
        {
            continue;
        }
        
        if (!strcmp(buf, "quit\n"))
        {
            printf("退出成功\n");
            break;
        }
        printf("\n客户端：%s\n", buf);
    }
    return NULL;
}
void* pthread_serve_write(void * soc)
{   TCP_soc soc_1 = *(TCP_soc*)soc;
    char buf[128];
    while (1)
    {
               // 发送信息
        memset(buf, 0, sizeof(buf));

        printf("服务器：");
        fgets(buf, sizeof(buf), stdin);
        buf[strlen(buf) - 1] = '\0';
        write(soc_1.acc_fd, buf, strlen(buf));
        if (!strcmp(buf, "quit\n"))
        {
            printf("退出成功\n");
            break;
        }
        // printf("发送的信息是[%s]\n", buf);
    }
    return NULL;
}